package com.leoandroid.tool.toolsbox.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;

import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.leoandroid.tool.toolsbox.largeread.R;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropActivity;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Utils {

    //加载弹窗
    public static AlertDialog loadDialog;
    public static void LoadingDialog(Context context) {
        try {
            ((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(((Activity)context).getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        } catch(Exception e) {
        }
        loadDialog = new MaterialAlertDialogBuilder(context)
                .create();
        final View contentView = View.inflate(context, R.layout.loading, null);
        loadDialog.setView(contentView);
        loadDialog.show();
        loadDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#00000000")));
        WindowManager.LayoutParams layoutParams = loadDialog.getWindow().getAttributes();
        layoutParams.width = context.getResources().getDisplayMetrics().widthPixels / 5 * 4;
        layoutParams.height = context.getResources().getDisplayMetrics().widthPixels / 5 * 4;
        loadDialog.getWindow().setAttributes(layoutParams);
    }

    //保存图片
    public static String SaveImage(Context context, Bitmap bitmap, String path, String name) {
        if (bitmap == null) {
            return null;
        }
        @SuppressLint("SimpleDateFormat")
        final String time = new SimpleDateFormat("HH-mm-ss").format(new Date());
        if (!FileUtil.isExistFile(FileUtil.getExternalStorageDir().concat(path))) {
            FileUtil.makeDir(FileUtil.getExternalStorageDir().concat(path));
        }
        File appDir = new File(FileUtil.getExternalStorageDir().concat(path));
        File file = new File(appDir, name);
        java.io.FileOutputStream fos = null;
        try {
            fos = new java.io.FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            return file.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (java.io.IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    //裁剪图片
    @SuppressLint("WrongConstant")
    public static String startUCrop(Context context, String sourceFilePath, float aspectRatioX, float aspectRatioY) {

        if (TextUtils.isEmpty(sourceFilePath)){
            Toast.makeText(context,"获取图片失败，请您检查您的存储权限",Toast.LENGTH_SHORT).show();
            return "";
        }

        Uri sourceUri = Uri.fromFile(new File(sourceFilePath));
        File outDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        if (!outDir.exists()) {
            outDir.mkdirs();
        }
        File outFile = new File(outDir, ".Crop.jpg");
        //裁剪后图片的绝对路径
        String cameraScalePath = outFile.getAbsolutePath();
        Uri destinationUri = Uri.fromFile(outFile);
        //初始化，第一个参数：需要裁剪的图片；第二个参数：裁剪后图片
        UCrop uCrop = UCrop.of(sourceUri, destinationUri);
        //初始化UCrop配置
        UCrop.Options options = new UCrop.Options();
        //设置裁剪图片可操作的手势
        options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL);
        //是否隐藏底部容器，默认显示
        options.setHideBottomControls(false);
        //设置toolbar颜色
        //options.setToolbarColor(ActivityCompat.getColor(activity, R.color.appbarColor));
        //设置状态栏颜色
        //options.setStatusBarColor(ActivityCompat.getColor(activity, R.color.appbarColor));
        //是否能调整裁剪框
        //options.setFreeStyleCropEnabled(true);
        //UCrop配置
        uCrop.withOptions(options);
        //设置裁剪图片的宽高比，比如16：9
        uCrop.withAspectRatio(aspectRatioX, aspectRatioY);
        //uCrop.useSourceImageAspectRatio();
        //跳转裁剪页面
        uCrop.start((Activity) context);
        return cameraScalePath;
    }
}
